package com.ruoyi.file.controller;

import cn.hutool.core.util.StrUtil;
import com.ruoyi.common.core.web.domain.AjaxResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.utils.file.FileUtils;
import com.ruoyi.file.service.ISysFileService;
import com.ruoyi.system.api.domain.SysFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 文件请求处理
 * 
 * @author ruoyi
 */
@RestController
public class SysFileController
{
    private static final Logger log = LoggerFactory.getLogger(SysFileController.class);

    /**
     * 资源映射路径 前缀
     */
    @Value("${file.prefix}")
    public String localFilePrefix;

    /**
     * 域名或本机访问地址
     */
    @Value("${file.domain}")
    public String domain;

    /**
     * 上传文件存储在本地的根路径
     */
    @Value("${file.path}")
    private String localFilePath;

    @Autowired
    private ISysFileService sysFileService;

    /**
     * 文件上传请求
     */
    @PostMapping("uploads")
    public R<Map<String,Object>> uploads(List<MultipartFile> file)
    {
        try
        {
            Map<String,Object> map = new HashMap<>();
            SysFile sysFile = new SysFile();
            for (MultipartFile multipartFile : file) {
                // 上传并返回访问地址
                String url = sysFileService.uploadFile(multipartFile);
                // 找到最后一个点的位置
                int lastDotIndex = url.lastIndexOf('.');
                String charactersAfterLastDot = url.substring(lastDotIndex + 1);

                sysFile.setName(FileUtils.getName(url));
                sysFile.setUrl(url);
                sysFile.setFileExtension(charactersAfterLastDot);
                sysFile.setSize(multipartFile.getSize());
                map.put(sysFile.getName(),sysFile);
            }
            return R.ok(map);
        }
        catch (Exception e)
        {
            log.error("上传文件失败", e);
            return R.fail(e.getMessage());
        }
    }

    /**
     * 文件上传请求
     */
    @PostMapping("upload")
    public R<SysFile> upload(MultipartFile file)
    {
        try
        {
            // 上传并返回访问地址
            String url = sysFileService.uploadFile(file);
            // 找到最后一个点的位置
            int lastDotIndex = url.lastIndexOf('.');
            String charactersAfterLastDot = url.substring(lastDotIndex + 1);
            SysFile sysFile = new SysFile();
            sysFile.setName(FileUtils.getName(url));
            sysFile.setUrl(url);
            sysFile.setFileExtension(charactersAfterLastDot);
            sysFile.setSize(file.getSize());
            return R.ok(sysFile);
        }
        catch (Exception e)
        {
            log.error("上传文件失败", e);
            return R.fail(e.getMessage());
        }
    }


    @GetMapping("/downloadTemplate")
    public ResponseEntity<InputStreamResource> downloadFile() throws IOException {
        String fileName = "单位导入模板.xlsx";
        ClassPathResource resource = new ClassPathResource(fileName);
        InputStreamResource inputStreamResource = new InputStreamResource(resource.getInputStream());
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"))
                .contentType(MediaType.parseMediaType("application/vnd.ms-excel"))
                .body(inputStreamResource);
    }
    /**
     * 通用下载请求
     *
     * @param url
     */
    @GetMapping("download")
    public AjaxResult fileDownload(String url, HttpServletResponse response, HttpServletRequest request) {
        try {
//            //去掉头部部分
            String s = StrUtil.removePrefix(url, domain);
            //将static替换成原始路径
            String replace = s.replace(localFilePrefix, localFilePath);
//             path是指想要下载的文件的路径
//            String s = "D:\\text\\2023\\11\\12\\11.JPG";

            File file = new File(replace);
            log.info(file.getPath());
            // 获取文件名
            String filename = file.getName();
            // 获取文件后缀名
            String ext = filename.substring(filename.lastIndexOf(".") + 1).toLowerCase();
            log.info("文件后缀名：" + ext);
            // 将文件写入输入流
            FileInputStream fileInputStream = new FileInputStream(file);
            InputStream fis = new BufferedInputStream(fileInputStream);
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();

            // 清空response
            response.reset();
            // 设置response的Header
            response.setCharacterEncoding("UTF-8");
            //Content-Disposition的作用：告知浏览器以何种方式显示响应返回的文件，用浏览器打开还是以附件的形式下载到本地保存
            //attachment表示以附件方式下载   inline表示在线打开   "Content-Disposition: inline; filename=文件名.mp3"
            // filename表示文件的默认名称，因为网络传输只支持URL编码的相关支付，因此需要将文件名URL编码后进行传输,前端收到后需要反编码才能获取到真正的名称
            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
            // 告知浏览器文件的大小
            response.addHeader("Content-Length", "" + file.length());
            OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            outputStream.write(buffer);
            outputStream.flush();
        } catch (IOException ex) {
            ex.printStackTrace();
            return  AjaxResult.error("文件下载失败");
        }
        return AjaxResult.success();
    }

}